package com.raymond.queue.codec.encodeing;

import com.raymond.queue.common.codec.annotation.MsgCodec;
import com.raymond.queue.common.codec.encodeing.BaseEncoder;
import com.raymond.queue.common.enums.CommandIdType;
import com.raymond.queue.common.msg.BaseMessage;
import com.raymond.queue.common.msg.response.ConsumptionMsgResponse;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.util.List;

/**
 * 消息消费响应编码器
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-07-14 15:13
 */
@MsgCodec(commandId = CommandIdType.CONSUMPTION_RESP)
public class ConsumptionResponseEncoder extends BaseEncoder {

    @Override
    public byte[] encode0(BaseMessage msg) {
        ConsumptionMsgResponse consumptionMsgResponse = (ConsumptionMsgResponse) msg;
       int length = 4;
        ByteBuf buffer = Unpooled.buffer();
        buffer.writeInt(consumptionMsgResponse.getCode());
        if (consumptionMsgResponse.getData() != null) {
            List<byte[]> data = consumptionMsgResponse.getData();
            for (byte[] datum : data) {
                buffer.writeInt(datum.length);
                buffer.writeBytes(datum);
                length += datum.length + 4;
            }
        }
        byte[] body = new byte[length];
        buffer.readBytes(body);
        return body;
    }
}
